import * as Koa from 'koa';
import * as bodyParser from 'koa-bodyparser';
import * as KoaStatic from 'koa-static';
import * as helmet from 'koa-helmet';

import { loggerMiddleware } from './utils/log4js';
import { errorHandler, responseHandler } from './utils/response';
import privateRouter from './routes/private';
import publicRouter from './routes/public';
import Seq from './utils/sequelize';
const Sequelize = new Seq();
const app = new Koa();

//处理前端跨域
app.use(async (ctx, next) => {
    ctx.set("Access-Control-Allow-Origin", ctx.request.header.origin)
    ctx.set("Access-Control-Allow-Credentials", 'true');
    ctx.set("Access-Control-Max-Age", '86400000');
    ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");
    ctx.set("Access-Control-Allow-Headers", "x-requested-with, accept, origin, content-type");
    await next()
    // if (ctx.method == 'OPTIONS') {
    //     ctx.body = 200;
    // } else {
    //     await next();
    // }
});
//日志文件记录
app.use(loggerMiddleware);
//错误日志输出
app.use(errorHandler);
//请求格式化
app.use(bodyParser());
//API
app.use(publicRouter.routes());
app.use(publicRouter.allowedMethods());
app.use(privateRouter.routes());
app.use(privateRouter.allowedMethods());
//响应日志输出
app.use(responseHandler);
//安全设置
app.use(helmet());
//静态资源访问
// app.use(KoaStatic('./public'));
app.listen(4211);

console.log('Server running on port 4211');